package cn.huihuo.weibo.controller;

import cn.huihuo.weibo.bean.comment.CommentPage;
import cn.huihuo.weibo.bean.comment.CommonResult;
import cn.huihuo.weibo.module.Comment;
import cn.huihuo.weibo.module.Message;
import cn.huihuo.weibo.service.CommentService;
import cn.huihuo.weibo.service.ParticipationService;
import cn.huihuo.weibo.utils.TimeUtils;
import cn.jfinalbbs.common.BaseController;
import cn.jfinalbbs.common.Constants;
import cn.jfinalbbs.user.User;
import cn.jfinalbbs.utils.Result;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;

/**
 * @author Dan
 *         Created by zhengjunbo on 2015/10/5.
 */
public class CommentController extends BaseController {

    /**
     * 获取商品评论的评论
     */
    public void getComment() {
        String ugcid = getPara("ugcid");
        Integer pageStep = getParaToInt("pageStep");//页面
        Integer count = getParaToInt("count");
        CommentPage commentPage = CommentService.commentService.getCommentPage(pageStep, count, ugcid);
        renderJson(commentPage);
    }



    //保存评论的评论
    public void saveComment() {
        String ugcId = getPara("ugcId");

        String commentContent = getPara("commentContent");


        String cid = getPara("cid");

        String replayUserId = getPara("replayUserId");
        String replayUserName = getPara("commentReplyUserName");


        User user = getSessionAttr(Constants.USER_SESSION);
        if(user==null){
            error("请登录后添加！");
            return;
        }

        CommonResult commonResult ;
        try {
            commonResult = CommentService.commentService.saveComment(ugcId, commentContent, cid, user.getStr("id"),replayUserId);
            commonResult.setCommentAvatar(user.getStr("avatar"));
            commonResult.setUserId(user.getStr("id"));
            commonResult.setReplayUserId(replayUserId);
            commonResult.setCommentUserName(user.getStr("nickname"));
            commonResult.setCommentReplyUserName(replayUserName);
            commonResult.setCommentUserUrl("/user/"+user.getStr("id"));
            commonResult.setCommentReplyUserUrl("/user/" + replayUserId);


        } catch (Exception e) {
            error("保存失败！");
            e.printStackTrace();
            return;
        }
        renderJson(new Result(Constants.ResultCode.SUCCESS, "保存成功!", commonResult));
    }

    //保存

    public void delete() {
        Integer cid = getParaToInt("cid");
        if (cid == null) {
            throw new RuntimeException("删除评论失败！");
        }


        Message.dao.deleteMessage(cid);

        List<Comment> comments = Comment.comment.findByReplayCommId(cid);
        for (Comment comment : comments){
            Message.dao.deleteMessage(comment.getInt("id"));
         }

        boolean b = Comment.comment.deleteById(cid);
        if(!b){
            throw new RuntimeException("删除评论失败！");
        }
        success();
    }


}
